$(function() {

	var errorFiles = new Array();
	var hasError = false;
	var hasFileUploaded = false;
	var init = 0;

	$('#file_upload').uploadify({
		swf : '../resources/js/uploadify.swf',
		uploader : 'uploadFile',
		fileObjName : 'file',
		buttonText : 'Selecionar XMLs',
		auto : true,
		checkExisting: false,
		fileTypeDesc: 'Apenas XML',
		fileTypeExts: '*.xml',
		progressData: 'percentage',
		queueSizeLimit: 400,
		uploadLimit: 400,
		width: 180,
		
		
		onUploadStart: function() {

			if (init == 0) {
			
				errorFiles = new Array();
				hasError = false;
				hasFileUploaded = false;
				$("#painelError").hide();
				$("#painelError .panel-body span").empty();
				init++;
				
			}
			

		},

		onUploadSuccess: function(file){
			hasFileUploaded = true;
		},
		
		onClearSpan : function() {
			
		},

		onUploadError: function(file){
			errorFiles.push(file);
			hasError = true;
		},

		onQueueComplete : function() {

			if (!hasError) {
				window.location = '../upload/toDownload';
			}else{

				$("#painelError").fadeIn();

				var i = 0;
				$(errorFiles).each(function(){

					$("#filesError").append( errorFiles[i].name ).append("<br />");

					i++;

				});

				if (hasFileUploaded) {
					getNumberFile();
					$("#painelSuccess").fadeIn();

				}
			}
			
			init = 0;
			

		}

	});
	
	$("#linkDownload").click(function() {
		
		$("#painelSuccess").fadeOut();
		
	});
	
	
	function getNumberFile() {
		
		$.ajax({
			type    : 'POST',
			async   : true,
			url     : 'fileNumberVariable',
			success : function(data) {
				$("#linkDownload").attr("href", "../DownloadServlet?fileName="+data);
			}
		});
		
	}
	
	
	
});